#!/bin/bash

LINK_PATH="/usr/local/bin/tsc-cli"
URL="https://gitee.com/api/v5/repos/WeCanSTU/TechSync/releases/latest"

# Function to add udev rules if they don't already exist
add_udev_rule() {
  HIDRAW_RULE_FILE="/etc/udev/rules.d/99-hidraw-permissions.rules"
  HIDRAW_RULE='SUBSYSTEM=="hidraw", ATTRS{idVendor}=="3743", ATTRS{idProduct}=="a022", MODE="0666", GROUP="plugdev"'

  TTY_RULE_FILE="/etc/udev/rules.d/99-tty-permissions.rules"
  TTY_RULE='SUBSYSTEM=="tty", ATTRS{idVendor}=="3743", ATTRS{idProduct}=="a022", MODE="0666", GROUP="dialout"'

  # Add HIDRAW rule if it doesn't exist
  if [ -f "$HIDRAW_RULE_FILE" ]; then
    if ! grep -q "$HIDRAW_RULE" "$HIDRAW_RULE_FILE"; then
      echo "$HIDRAW_RULE" | sudo tee -a "$HIDRAW_RULE_FILE" > /dev/null
    fi
  else
    echo "$HIDRAW_RULE" | sudo tee "$HIDRAW_RULE_FILE" > /dev/null
  fi

  # Add TTY rule if it doesn't exist
  if [ -f "$TTY_RULE_FILE" ]; then
    if ! grep -q "$TTY_RULE" "$TTY_RULE_FILE"; then
      echo "$TTY_RULE" | sudo tee -a "$TTY_RULE_FILE" > /dev/null
    fi
  else
    echo "$TTY_RULE" | sudo tee "$TTY_RULE_FILE" > /dev/null
  fi

  # Reload udev rules and trigger
  sudo udevadm control --reload-rules
  sudo udevadm trigger
}

# Functions to check and install tools on Ubuntu
check_install_ubuntu() {
  PACKAGE=$1
  if ! dpkg -s $PACKAGE >/dev/null 2>&1; then
    echo "$PACKAGE is not installed. Installing..."
    sudo apt-get update
    sudo apt-get install -y $PACKAGE
  fi
}

# Functions to check and install tools on macOS
check_install_macos() {
  PACKAGE=$1
  if ! brew list $PACKAGE >/dev/null 2>&1; then
    echo "$PACKAGE is not installed. Installing..."
    brew install $PACKAGE
  fi
}

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  OS="ubuntu"
  FILE_PREFIX="TechSync-linux"
  FILE_EXT=".deb"
elif [[ "$OSTYPE" == "darwin"* ]]; then
  OS="macos"
  FILE_PREFIX="TechSync-mac"
  FILE_EXT=".app"
else
  echo "Unsupported OS: $OSTYPE"
  exit 1
fi

download_and_extract() {
  ASSET_URLS=$(curl -s $URL | jq -r '.assets[].browser_download_url' | grep "$FILE_PREFIX" | grep -E ".zip|.z01")
  
  if [ -z "$ASSET_URLS" ]; then
    echo "No release assets found for $OS."
    exit 1
  fi

  TEMP_DIR=$(mktemp -d)
#  echo "Downloading files to: $TEMP_DIR"
  for URL in $ASSET_URLS; do
    FILENAME=$(basename $URL)
#    echo "Downloading: $URL as $FILENAME"
    wget -q --show-progress $URL -O "$TEMP_DIR/$FILENAME"
  done

  ZIP_FILE=$(find $TEMP_DIR -name "*.zip" | head -n 1)
  if [ -f "$ZIP_FILE" ]; then
    echo "Fixing and unzipping the archive..."
    FULL_ZIP="$TEMP_DIR/${FILE_PREFIX}-full.zip"
    zip -FF $ZIP_FILE --out $FULL_ZIP >/dev/null 2>&1 
    unzip -o $FULL_ZIP -d $TEMP_DIR >/dev/null 2>&1
  else
    echo "Failed to create merged ZIP file. Check file names and availability."
    exit 1
  fi

  if [[ "$OS" == "ubuntu" ]]; then
    FILE_PATH="${ZIP_FILE%.zip}.deb"
    sudo dpkg -i $FILE_PATH
    sudo apt-get install -f -y
    rm -rf $TEMP_DIR
    if [ ! -L "$LINK_PATH" ]; then
      sudo ln -s /opt/TechSync/resources/extraResources/bin/tsc-cli "$LINK_PATH"
    fi
    add_udev_rule
    echo "Installation completed on Ubuntu."

  elif [[ "$OS" == "macos" ]]; then
    FILE_PATH="${ZIP_FILE%.zip}.dmg"
    # Attach the DMG and capture the output
    ATTACH_OUTPUT=$(hdiutil attach "$FILE_PATH" -nobrowse)

    # Extract the correct volume mount point
    MOUNT_POINT=$(echo "$ATTACH_OUTPUT" | grep '/Volumes/' | awk '{for(i=3;i<=NF;++i) printf "%s ", $i; print ""}' | xargs)

    if [ -d "$MOUNT_POINT/TechSync.app" ]; then
      cp -r "$MOUNT_POINT/TechSync.app" /Applications
    fi
    # Detach the volume safely
    hdiutil detach "$MOUNT_POINT" -quiet
    rm -rf $TEMP_DIR
    if [ ! -L "$LINK_PATH" ]; then
      sudo ln -s /Applications/TechSync.app/Contents/Resources/extraResources/bin/tsc-cli "$LINK_PATH"
    fi
    echo "Installation completed on macOS."
  fi
}

if [ "$OS" == "ubuntu" ]; then
  check_install_ubuntu wget unzip zip
  check_install_ubuntu jq
  download_and_extract
elif [ "$OS" == "macos" ]; then
  check_install_macos wget unzip zip
  check_install_macos jq
  download_and_extract
else
  echo "Unsupported OS for installation."
  exit 1
fi